using System;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using ExamServer.Service;
using ExamServer.Models;
using AutoMapper;
using Newtonsoft.Json;
using ExamServer.Entities;
using ExamServer.Helpers;

namespace ExamServer.Controllers
{
  [ApiController]
  [Route("[controller]")]
  public class UserController : ControllerBase
  {
    private readonly IRepositoryWrapper wrapper;
    private readonly IMapper mapper;

    public UserController(IRepositoryWrapper wrapper,
                          IMapper mapper)
    {
      this.wrapper = wrapper;
      this.mapper = mapper;
    }
    #region 查询
    ///<summary>
    /// 分页查询
    ///</summary>
    [HttpGet]
    public async Task<IActionResult> Get([FromQuery] UsersResourceParameters parameters)
    {
      var userlistAll =await wrapper.Users.GetAllAsync();
                           // .Skip(parameters.PageSize*(parameters.PageNumber-1))
                            //.Take(parameters.PageSize);
      if (userlistAll != null)
      {
       // userlistAll =userlistAll.Where(x=>x.Name.Contains(parameters.Name)&&x.Email.Contains(parameters.Email));
       var userlist= userlistAll.Skip(parameters.PageSize*(parameters.PageNumber-1))
       .Take(parameters.PageSize); //分页查询

        var userModelList = mapper.Map<IEnumerable<UserModel>>(userlist);
        return new JsonResult(new
        {
          total =userlistAll.Count(),
          rows = userModelList.ToList()
        });
      }
      return NotFound();
    }
    
    ///<summary>
    /// 根据ID获取用户对象
    ///</summary>
    [HttpGet("{id}")]
    public async Task<IActionResult> GetByIdAsync(string id){
      var user =await wrapper.Users.GetByIdAsync(Guid.Parse(id));
      if(user==null){
        return NotFound();
      }
      var usermodel = mapper.Map<UserEditModel>(user);
      return Ok(usermodel);
    }
    #endregion
    #region 登录
    [HttpPost]
    public async Task<IActionResult> Login([FromForm]string uname,
        [FromForm]string pwd)
    {
      var result = await wrapper.Users.Login(uname, pwd);
      var model = mapper.Map<UserModel>(result);
      return new JsonResult(new
      {
        status = result != null ? true : false,
        message = result != null ? "登录成功" : "登录失败",
        user = model
      });
    }
    #endregion
    #region 添加用户
    [HttpPost]
    [Route("Add")]
    public async Task<IActionResult> Add([FromForm]AddNewUserModel newModel)
    {
      var userList = (await wrapper.Users.GetByConditionAsync(x => x.Name == newModel.Name)).ToList();
      if (userList.Count == 0)
      {
        Users newUser = new Users();
        newUser.Id = Guid.NewGuid();
        newUser.Name = newModel.Name;
        newUser.Password = newModel.Password;
        newUser.Birthday = newModel.Birthday;
        newUser.Email = newModel.Email;
        newUser.Remark = newModel.Remark;
        wrapper.Users.Creatre(newUser);
        bool bl = await wrapper.Users.SaveAsync();
        return new JsonResult(new
        {
          status = bl,
          message = bl ? "添加成功" : "添加失败"
        });
      }
      else
      {
        return new JsonResult(new
        {
          status = false,
          message = "该用户名已存在"
        });
      }
    }
    #endregion
    
    #region 修改用户
    [HttpPut]
    public async Task<IActionResult> Update([FromForm]UserEditModel usermodel)
    {
      var user =await wrapper.Users.GetByIdAsync(usermodel.Id);
      user.Name=usermodel.Name;
      user.Birthday =usermodel.Birthday;
      user.Email =usermodel.Email;
      user.Remark =usermodel.Remark;      
      wrapper.Users.Update(user);
      bool bl = await wrapper.Users.SaveAsync();
      return new JsonResult(new{
        status=bl,
        message=bl?"修改成功":"修改失败"
      });
    }
    #endregion
    
    #region 删除用户
    [HttpDelete]
    public async Task<IActionResult> Delete([FromForm]string id){
      var user =await wrapper.Users.GetByIdAsync(Guid.Parse(id));
      wrapper.Users.Delete(user);
      bool bl=  await wrapper.Users.SaveAsync(); 
      return new JsonResult(new{
        status=bl,
        message=bl ? "删除成功" : "删除失败"
      });
    }
    #endregion
  }

}